package Server.server.impl;

import Server.provider.ServiceProvider;
import Server.server.RpcServer;
import Server.server.work.WorkThread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolRPCServer implements RpcServer {

    // 定义一个线程池对象threadPool，用于管理和执行线程任务
    private final ThreadPoolExecutor threadPool;
    private ServiceProvider serviceProvider;

    // 创建一个线程池，核心线程数等于CPU的核心数，最大线程数1000，非核心线程的存活时间60秒，队列大小为100
    public ThreadPoolRPCServer(ServiceProvider serviceProvider,
                               int corePoolSize,
                               int maximumPoolSize,
                               long keepAliveTime,
                               TimeUnit unit,
                               BlockingDeque<Runnable> workQueue) {
        threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        this.serviceProvider = serviceProvider;
    }

    @Override
    public void start(int port) {
        System.out.println("服务端启动");
        try {
            // 创建一个ServerSocket实例，在端口监听
            ServerSocket serverSocket = new ServerSocket(port);
            while (true) {
                // 接受连接，通过accept()方法阻塞，直到有连接请求
                Socket socket = serverSocket.accept();
                // 打印socket连接信息和连接id
                System.out.println("socket连接信息：" + socket);
                // 使用线程池分发任务，每个客户端请求交给线程池处理
                threadPool.execute(new WorkThread(socket, serviceProvider));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void stop() {

    }
}
